<?php
/**
 * PHP Framework Artificial Intelligence Choice Tree class
 * This class is base for all classes which implement intellectual search
 *
 * @author Andrew <andrew@vitche.com>
 * @author Frozen Rain <frozenrain@mail.ru>
 **/
abstract class ChoiceTree {

    /**
     * Last extracted choice node
     **/
    protected $_lastNode = null;

    /**
     * Current choice space
     **/
    protected $_space = array();

    /**
     * Creates a new instance for the ChoiceTree class using the initial node
     * specified
     *
     * The initial node is added to the search space array and becomes the
     * root of the tree
     **/
    public function __construct($initialNode) {

        array_push($this->_space, $initialNode);
    }

    /**
     * Checks whether the search is finished
     * The base implementation considers search to be finished when the search
     * space is empty
     * @return boolean
     **/
    protected function checkFinished() {

        return 0 == count($this->_space);
    }

    /**
     * Expands the given node
     * In the base implementation the expansion algorithm is not defined and
     * therefore an empty array is returned
     **/
    protected function expand(&$node) {

        return array();
    }

    /**
     * @return mixed The last node popped from the list of available ones
     **/
    public function getLastNode() {

        return $this->_lastNode;
    }

    /**
     * Extracts the next choice node from the list of available ones
     **/
    protected function pop() {

        return array_pop($this->_space);
    }

    /**
     * Processes the full intellectual search until the stop condition is met
     **/
    public function process() {

        while(!$this->checkFinished()) {

            $this->_lastNode = $this->pop();
            if (isset($this->_lastNode)) {

                $arChildNodes = $this->expand($this->_lastNode);
                $this->_space = array_merge($this->_space, $arChildNodes);
            }
        }
    }
}
?>